#include <stdlib.h>
#include <stdio.h>

#include "myLib.h"
#include "text.h"


typedef struct {
	int row;
	int col;
	int rdel;
	int cdel;
	int height;
	int width;
	u16 color;
} MOVOBJ;

#define NUMOBJS 7

int main()
{
	int i;
	u16 bgcolor = DKGRAY;
	int deltas[] = {-2, -1, 1, 2};
	u16 colors[] = {RED, GREEN, BLUE, MAGENTA, CYAN, YELLOW, WHITE};
	//int r,c;
	//unsigned char ch = 0;
	int size = 5;
	int score = 0;
	int oldsize = size;
	char buffer[41];
	
	REG_DISPCTL = MODE3 | BG2_ENABLE;
	
	MOVOBJ objs[NUMOBJS];
	MOVOBJ oldobjs[NUMOBJS];
	MOVOBJ *ptr;
/*	
	for(i=0; i<38400; i++)
	{
		videoBuffer[i] = bgcolor;
	}
*/

	DMA[3].src = &bgcolor;
	DMA[3].dst = videoBuffer;
	DMA[3].cnt = 38400  | DMA_ON | DMA_SOURCE_FIXED;	
	for(i=0; i<NUMOBJS; i++)
	{
		objs[i].row = SCREENHEIGHT/2 - 40 + rand()%80;
		objs[i].col = SCREENWIDTH/2 - 40 + rand()%80;
		objs[i].rdel = deltas[rand()%4];
		objs[i].cdel = deltas[rand()%4];
  		objs[i].color = colors[i%7];
  		oldobjs[i] = objs[i]; 
  	}

	/*
	for(r=0; r<16; r++)
	{
		for(c = 0; c<16; c++)
		{
			drawChar(r*9, c*7, ch++, RED);
		}
	}
	while(1);
	*/
	// The Game Loop	
	
	while(1)
	{
		if(KEY_DOWN_NOW(BUTTON_UP))
		{
			size++;
			if(size>150) size = 150;
		}
		if(KEY_DOWN_NOW(BUTTON_DOWN))
		{
			size--;	
			if(size<3) size = 3;
		}	
		// Move the object

		for(i=0; i<NUMOBJS; i++)
		{
			ptr = objs+i;

			ptr->row += ptr->rdel;
			ptr->col += ptr->cdel;
		
			// Check for collisions
			if(ptr->row<0)
			{
				ptr->row = 0;
				ptr->rdel = -ptr->rdel;
				score++;
			}
			if(ptr->row>SCREENHEIGHT-1-size)
			{
				ptr->row = SCREENHEIGHT-1-size;
				ptr->rdel = -ptr->rdel;
			}
			if(ptr->col < 0)
			{
				ptr->col = 0;
				ptr->cdel = -ptr->cdel;
			}
			if(ptr->col > SCREENWIDTH-1-size)
			{
				ptr->col = SCREENWIDTH - 1-size;
				ptr->cdel = -ptr->cdel;
			}
		
		}
		
		sprintf(buffer, "Score: %d", score);
				
		waitForVblank();		// Draw the object
		drawRect(150, 5, 8, 15*6, bgcolor);		
		drawString(150, 5, buffer, RED);
		for(i=0; i<NUMOBJS; i++)
		{
		
		
			// Erase the object
			drawRect(oldobjs[i].row, oldobjs[i].col, oldsize, oldsize, bgcolor);
			
		}
		for(i=0; i<NUMOBJS; i++)
		{
		
		
			// Draw the object
			drawRect(objs[i].row, objs[i].col, size, size, objs[i].color);
			oldsize = size;
			oldobjs[i] = objs[i];
		}
		
	}
}


void delay(int n)
{
	int i;
	volatile int a;
	for(i=0; i<n*1000; i++)
	{
		a++;
	}
}
